﻿​<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link id="css" href="style.css" rel="stylesheet"/>
<title>人數統計平台</title>

<div id="content">
<div id="top"></div>
<div id="top"></div>
<div id="header1">
<h><img src="images/line.png" width="6" height="26" /> Total Area 總面積</h>
<table id="meters">
  <tr>
    <td id="TotalArea" class="INFO">0</td>
  </tr>
  <tr>
    <td>sq meters</td>
  </tr>
</table>

</div>
<div id="header2">
<h><img src="images/line.png" width="6" height="26" /> Total People 總人數</h>
<table id="people">
  <tr>
    <td id="TotalPeople" class="INFO">0</td>
  </tr>
  <tr>
    <td>peoples</td>
  </tr>
</table>
</div>


<div id="mapEditArea">
<table id="mapEdit">
  <tr>
    <td id="file">
    <button id="btn-save" type="button" onClick='save()'></button>
    <button id="btn-load" type="button" onClick='load()'></button>
    <select size="1" id="lengthListBox" style="width:150" onChange="">
      <option value="0">請選擇</option>
    </select>
    </td>
  </tr>
  <tr>
    <td id="googleMap">
    <div id="map_canvas">
       <input id="pac-input" class="controls" type="text" placeholder="Search Box">
        <div id="map" class="MAP"></div>
    </div>
    </td>
  </tr>
  <tr>
    <td valign="baseline" id="edit">
    <input type="checkbox" class="Toggle_Markers" onclick="showMarkers();">
    <label for="checkbox">隱藏圖示</label>
     <img src="images/police.png" width="25" height="25" />
    <input id="rester" onclick="deleteLast()" type="button" class="Delete_Last_Point_button">
    <input id="delete" onclick="deletePoints()" type="button" class="Delete_all_button">
    <input id="add" onclick="newItem()" type="button" class="New_Polygon_button">
     
    </td>
   </tr>
</table>
<div id="footer1">
<h><img src="images/line.png" width="6" height="26" /> Other 其他資訊</h>
</div>
<div id="footer2">
<table id ="PolyInfo" class="highlight" >
    <tbody >
	<tr>
		<th>編號</th><th>面積 (平方公尺)</th><th>密度 (人數/平方公尺)</th><th>人數</th>
	</tr>
	</tbody> 
</div>

 <input onclick="refreshTable();" type="button" value="delet all rows">
  <input onclick="store();" type="button" value="Store">
 <input onclick="readtxt();" type="button" value="Return">
</div>
</head>

<body onload="initialize()">
    <script type="text/javascript" src="jquery-1.7.1.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
    <script type="text/javascript" src="maplabel.js"></script>
    <script type="text/javascript">
        var poly = [];
        var path = [];
        var map;
        var mapLabel = [];
        var markers = [];
        var density = [];
        var cnt = 0;
        var view = 1;
        var endPoint = [];
        var PolyID = [];
        var PolygonArea = [];
        var PeopleNum = [];

        function initialize() {
            //Set Map
            var JingFuGate = new google.maps.LatLng(25.039027, 121.517368);
            map = new google.maps.Map(document.getElementById("map"), {
                zoom: 18,
                center: JingFuGate,
                mapTypeId: google.maps.MapTypeId.SATELLITE
            });
			
            // Create the search box and link it to the UI element.
            var input = /** @type {HTMLInputElement} */ (
                document.getElementById('pac-input'));
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
            // [START region_getplaces]
            // Listen for the event fired when the user selects an item from the
            // pick list. Retrieve the matching places for that item.
            var searchBox = new google.maps.places.SearchBox(
                /** @type {HTMLInputElement} */
                (input));
            google.maps.event.addListener(searchBox, 'places_changed', function() {
                var places = searchBox.getPlaces();
                if (places.length == 0) {
                    return;
                }
                // For each place, get the icon, place name, and location.
                var bounds = new google.maps.LatLngBounds();
                for (var i = 0, place; place = places[i]; i++) {

                    bounds.extend(place.geometry.location);
                }
                map.fitBounds(bounds);
                map.setZoom(18);
            });
            // [END region_getplaces]
            // Bias the SearchBox results towards places that are within the bounds of the
            // current map's viewport.
            google.maps.event.addListener(map, 'bounds_changed', function() {
                var bounds = map.getBounds();
                searchBox.setBounds(bounds);
            });
			newPoly(0);
            // Add a listener for the Map.
            google.maps.event.addListener(map, 'click', addPoint);
            infoWindow = new google.maps.InfoWindow();
        }

        function newItem() {
			infoWindow.close(map);
            if (PolygonArea[cnt] >0) {
				cnt = cnt+1;
			if (PolygonArea[cnt]==null || PolygonArea[cnt]<=0)
				newPoly(cnt);
			}
        }
		
		
		function newPoly(num){
           path[num] = new google.maps.MVCArray;
            // Add Polygon.	
            poly[num] = new google.maps.Polygon({
                strokeWeight: 1,
                fillColor: '#FFFFFF',
                indexID: num,
                draggable: true
            });
            //poly[num].setMap(map);
            poly[num].setPaths(new google.maps.MVCArray([path[num]]));
			poly[num].setMap(null);
            poly[num].setMap(map);
            mapLabel[num] = new MapLabel({
                //position: JingFuGate,
                map: map,
                fontSize: 12,
                align: 'center'
            });
			initialTable();
            google.maps.event.addListener(poly[num], 'click', getDensityValue);
            google.maps.event.addListener(poly[num], 'rightclick', deletePoly);
            google.maps.event.addListener(poly[num], 'dragend', movePolygon);		
			google.maps.event.addListener(poly[num], 'mouseover',mouseoverPoly);
			google.maps.event.addListener(poly[num], 'mouseout',mouseoutPoly);		
		}
		function mouseoverPoly(event){
				var table = document.getElementById("PolyInfo");			
			   for (var i = 1; i<table.rows.length; i++) {
			   //iterate through rows
			   var value = table.rows[i].cells[0].innerHTML;
			   if (value ==this.indexID){		   
					table.rows[i].style.background = "#fefae5"; 
					//this.setOptions({fillColor: "#FFFF99"});
			   }
			}	
			//document.getElementById("PolyInfo").rows[1].style.background = "#FFFF99"; 
		}
		function mouseoutPoly(num){
				var table = document.getElementById("PolyInfo");			
			   for (var i = 1; i<table.rows.length; i++) {
			   //iterate through rows
			   var value = table.rows[i].cells[0].innerHTML;
			   //if (value ==this.indexID){		   
					table.rows[i].style = "#fefae5"; 
				//if (density[this.indexID] != null) {
					//this.setOptions({fillColor: "00ffff"});
				//}
				//else {	
					//this.setOptions({fillColor: "#FFFFFF"});
					//poly[temp].fillColor = '#FFFFFF';
				//}
			   //}
			}	
			//document.getElementById("PolyInfo").rows[1].style.background = "#FFFFCC"; 
		}
		

		function initialTable(){
		    var table = document.getElementById("PolyInfo");
			var length= table.rows.length;
			var row   = table.insertRow(length);
			var cell1 = row.insertCell(0);
			cell1.innerHTML=cnt;
			var cell2 = row.insertCell(1);
			var cell3 = row.insertCell(2);
			var cell4 = row.insertCell(3);
			row.onmouseover = function(){
				var temp = row.cells[0].innerHTML;
				poly[temp].setMap(null);
				poly[temp].setPaths(new google.maps.MVCArray([path[temp]]));
				poly[temp].fillColor = 'yellow';
				poly[temp].setMap(map);
			} 
			row.onmouseout  = function(){
				//cell1.innerHTML = "88";
				var temp = row.cells[0].innerHTML;
				poly[temp].setMap(null);
				//poly[cnt].setPaths(new google.maps.MVCArray([path[cnt]]));
				if (density[temp] != null) {
					poly[temp].fillColor = '#00ffff';
				}
				else {	
					poly[temp].fillColor = '#FFFFFF';
				}
				poly[temp].setMap(map);
			}
		
		}
		
        //Delete Poly
        function deletePoly(event) {
			PolyID = this.indexID;
            var html = "<table>" +
                "<tr><td></td><td><input type='button' value='Delete' onclick='deletePolygon()'/></td></tr>";
            infoWindow.setContent(html);
            infoWindow.setPosition(event.latLng);
            infoWindow.open(map);
        }
        function deletePolygon() {
			while (1){
				var index = endPoint.indexOf(PolyID);
				if (index > -1){
					markers[index].setMap(null);
					endPoint.splice(index, 1);
					markers.splice(index, 1);
					path[PolyID].removeAt(path[PolyID].length - 1);
				}
				else 
					break;
			}
			density[PolyID]=null;
			returnArea(density[PolyID], PolyID);
			infoWindow.close(map);
			var table = document.getElementById("PolyInfo");
			for (var i = 1; i<table.rows.length; i++) {
			   //iterate through rows
			   var value = table.rows[i].cells[0].innerHTML;
			   if (value ==PolyID){		   
			   table.deleteRow(i);
			   }
			}	
			if (table.rows.length==1){
				initialTable();
			}
			else{
				cnt = cnt+1;
				newPoly(cnt);
			}
        }		
		


        //Drag Polygon
        function movePolygon(event) {
            var len = poly[this.indexID].getPath().getLength();
            var htmlStr = "";
            for (var i = 0; i < len; i++) {
                htmlStr += poly[this.indexID].getPath().getAt(i).toUrlValue(5) + "<br>";
                markers[i + endPoint.indexOf(this.indexID)].setPosition(poly[this.indexID].getPath().getAt(i));
            }
            //document.getElementById('info1').innerHTML = htmlStr;
            returnArea(density[this.indexID], this.indexID);
        };



        //Density Input 
        function getDensityValue(event) {
            PolyID = this.indexID;
            var html = "<table>" +
                "<tr><td>Density:</td> <td><input type='text' id='name'/> </td> </tr>" +
                "<tr><td></td><td><input type='button' value='Save' onclick='saveData()'/></td><td><div id='warning' ></div></td></tr>";
            infoWindow.setContent(html);
            infoWindow.setPosition(event.latLng);
            infoWindow.open(map);
        }

        function saveData() {
			var input = document.getElementById("name").value;
			if (!isNaN(input)&& input>0){
            density[PolyID] = input
            returnArea(density[PolyID], PolyID);
            infoWindow.close(map);
            poly[PolyID].fillColor = '#00ffff';
            poly[PolyID].setMap(null);
            poly[PolyID].setMap(map);
			}
			document.getElementById('warning').innerHTML = "請輸入數字，PLZ ";
        }

        function returnArea(density, ind) {
            var Area = google.maps.geometry.spherical.computeArea(path[ind]);
            //document.getElementById('info').innerHTML = Area.toFixed(2) + " sq meters";
            //document.getElementById('info').innerHTML += "<br>" + (Area / (1000 * 1000)).toFixed(2) + " sq km";
            var bounds = new google.maps.LatLngBounds();
            var len = path[ind].length;
            if (len >= 3) {
                //poly[cnt].fillColor('005FF66');
                var points = path[ind].getArray();
                for (var n = 0; n < path[ind].length; n++) {
                    bounds.extend(points[n]);
                }
                if (density != null) {
                    var people = Math.round(density * Area);
                    //var str = 'People Num: ' + people + '\n' + 'Density: ' + density + '/m\u00b2' + 'Area :' + Area.toFixed(2);
                    var str ='NO.'+ind;
					mapLabel[ind].set('text', str);
					var Table = document.getElementById('PolyInfo');
					for (i=1;i<Table.rows.length-1;i++){
						if (ind==Table.rows[i].cells[0].innerHTML){
							break;
						}		
					}
					//Table.rows[TableLen].cells[0].innerHTML = ind;
					Table.rows[i].cells[1].innerHTML = Area.toFixed(2);
					Table.rows[i].cells[2].innerHTML = density;
					Table.rows[i].cells[3].innerHTML = people;
                } 
				else {
					var people = Math.round(density * Area);
                    //mapLabel[ind].set('text', Area.toFixed(2) + ' sq meters '+ind);
					mapLabel[ind].set('text','NO.'+ind);
					var Table = document.getElementById('PolyInfo');
					for (i=1;i<Table.rows.length-1;i++){
						if (ind==Table.rows[i].cells[0].innerHTML){
							break;
						}		
					}
					if(cnt==0){					
					Table.rows[1].cells[0].innerHTML = 0;
					}
					Table.rows[i].cells[1].innerHTML = Area.toFixed(2);
					Table.rows[i].cells[2].innerHTML = density;
					Table.rows[i].cells[3].innerHTML = people;
                }
                mapLabel[ind].set('position', bounds.getCenter());
                mapLabel[ind].setMap(map);
            }

            if (len <= 2) {
                mapLabel[ind].setMap(null);
            }
            PolygonArea[ind] = Area;
            PeopleNum[ind] = people;
            var TotalArea = 0;
            var TotalNum = 0;
            for (var i = 0; i < PolygonArea.length; i++) {
                if (PolygonArea[i] != null)
                    TotalArea += PolygonArea[i];
            }
            for (var i = 0; i < PeopleNum.length; i++) {
                if (PeopleNum[i] != null)
                    TotalNum += PeopleNum[i];
            }
            document.getElementById('TotalArea').innerHTML = TotalArea.toFixed(2);
            document.getElementById('TotalPeople').innerHTML = TotalNum;
        }

        //Mouse click event 
        function addPoint(event) {
            path[cnt].insertAt(path[cnt].length, event.latLng);
            var marker = new google.maps.Marker({
                position: event.latLng,
                map: map,
                draggable: true
            });
				poly[cnt].setMap(null);
				//poly[cnt].setPaths(new google.maps.MVCArray([path[cnt]]));
				if (density[cnt] != null) {
					poly[cnt].fillColor = '#00ffff';
				}
				else {	
					poly[cnt].fillColor = '#FFFFFF';
				}
				poly[cnt].setMap(map);            
            marker.setIcon('images/police.png');
            markers.push(marker);
            endPoint.push(cnt);
            returnArea(density[endPoint[markers.length - 1]], endPoint[markers.length - 1]);
            //google.maps.event.addListener(marker, 'click', function() {
            //	marker.setMap(null);
            //	for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
            //	markers.splice(i, 1);
            //	path[endPoint[i]].removeAt(i-endPoint.indexOf(endPoint[i]));
            //  });

            google.maps.event.addListener(marker, 'dragend', function() {
                for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
                path[endPoint[i]].setAt(i - endPoint.indexOf(endPoint[i]), marker.getPosition());
                returnArea(density[endPoint[i]], endPoint[i]);
            });
        }

        function showMarkers() {
			infoWindow.close(map);
            view = view * (-1);
            for (var i = 0; i < markers.length; i++) {
                if (view > 0)
                    markers[i].setMap(map);
                else
                    markers[i].setMap(null);
            }
        }


        // Deletes all markers in the array by removing references to them.
        function deletePoints() {
				infoWindow.close(map);
                for (var i = 0; i < markers.length; i++) {
                    markers[i].setMap(null);
                }
                endPoint = [];
                markers = [];
                PolygonArea = [];
                PeopleNum = [];
                density = [];
                cnt = 0;
                for (var i = 0; i < path.length; i++) {
                    path[i].clear();
                    mapLabel[i].setMap(null);
                }
                //document.getElementById('info').innerHTML = "0 sq meters";
                //document.getElementById('info').innerHTML += "<br>" + "0 sq km";
                //document.getElementById('info1').innerHTML = " ";
                document.getElementById('TotalArea').innerHTML = " ";
                document.getElementById('TotalPeople').innerHTML = " ";
                TotalArea = 0;
                TotalNum = 0;
				refreshTable();
				initialTable();
            }
            // Delete Last Point
        function deleteLast() {
			infoWindow.close(map);
            var ind = endPoint[markers.length - 1];
			var org =ind;
			if (path[ind]!= null)
			{
					
				if (path[ind].length == 1 && density[ind] != null) {
					density.pop();
				}
				markers[markers.length - 1].setMap(null);
				path[ind].removeAt(path[ind].length - 1);
				markers.pop();
				endPoint.pop();
				ind = endPoint[markers.length - 1];
				returnArea(density[ind], ind);
				if (cnt != 0) {
					cnt = ind;
				}	
			}
			if (org-ind !=0){
			    var table = document.getElementById("PolyInfo");
				table.deleteRow(table.rows.length -1);
				
			}
			returnArea(density[ind], ind);	

        }

        function store() {
            var len;
            var htmlStr = [];
            for (var j = 0; j <= cnt; j++) {
                len = poly[j].getPath().getLength();
                var tmp = "";
                for (var i = 0; i < len; i++) {
                    tmp += poly[j].getPath().getAt(i).toUrlValue(5) + "\n";
                }
                htmlStr[j] = tmp;
            }
			
            $.ajax({
                type: "POST",
                url: "saveInfor.php",
                data: {
                    density: density,
                    cnt: cnt,
                    coord: htmlStr
                },
				success: function(response) {
                        alert(response);
						alert('yes');
                },
				fail: function(response) {
                        alert(response);
						alert('fuck');
                }
            });
			
			

	
        }

        function readtxt() {


            $.ajax({
                type: "POST",
                url: "readtxt.php"

            }).done(function(o) {
                alert(o);

            });


        }
		
		// dynamic PolyInfo Talbe
		function refreshTable() {
			var table = document.getElementById("PolyInfo");
			for(var i = table.rows.length - 1; i > 0; i--)
			table.deleteRow(i);
		}		
    </script>

</body>
</html>
